package at.fhooe.mcm.lri.mdmpoc.actions;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import at.fhooe.mcm.lri.mdmpoc.warehouse.ServiceLocator;
import at.fhooe.mcm.lri.mdmpoc.warehouse.dao.TimingResultDao;
import at.fhooe.mcm.lri.mdmpoc.warehouse.datamodel.TimingResult;

import com.google.appengine.api.quota.QuotaService;
import com.google.appengine.api.quota.QuotaServiceFactory;

public abstract class WebAction {
	private long timeStart, timeStop;
	private long cpuStart, cpuEnd;
	private HttpServletRequest request;
	private QuotaService qs;

	public abstract void perform(HttpServletRequest request,
			HttpServletResponse response) throws Exception;

	public void startTiming() {
		qs = QuotaServiceFactory.getQuotaService();
		cpuStart = qs.getCpuTimeInMegaCycles();
		timeStart = System.currentTimeMillis();
	}

	public void endTiming(HttpServletRequest req, int itemCounter) {
		request = req;
		timeStop = System.currentTimeMillis();
		cpuEnd = qs.getCpuTimeInMegaCycles();
		TimingResultDao timingResultDao = ServiceLocator.getInstance()
				.getTimingResultDao();
		TimingResult tr = new TimingResult();
		tr.setAction(this.getClass().getName());
		tr.setDate(new Date());
		tr.setCpuMegaCycles(cpuEnd - cpuStart);
		tr.setCpuSeconds(qs.convertMegacyclesToCpuSeconds(cpuEnd - cpuStart));
		tr.setDuration(timeStop - timeStart);
		tr.setItems(itemCounter);
		if (request.getAttribute("UserID") != null) {
			String username = (String) request.getAttribute("UserID");
			tr.setUsername(username);
		} else {
			tr.setUsername("N/A");
		}
		Long key = new Long(timingResultDao.getNextFreeId()).longValue();
		tr.setKey(key);
		timingResultDao.insertTimingResult(tr);
		request.setAttribute("timing_CpuMegaCycles", tr.getCpuMegaCycles());
		request.setAttribute("timing_CpuSeconds", tr.getCpuSeconds());
		request.setAttribute("timing_duration", tr.getDuration());
	}
}